package com.seocoo.worker.order;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.contrarywind.view.WheelView;
import com.jaeger.library.StatusBarUtil;
import com.seocoo.worker.R;
import com.seocoo.worker.base.multiImage.BaseListImageFragment;
import com.seocoo.worker.base.multiImage.RspImage;
import com.seocoo.worker.friend.FriendEvaluateActivity;
import com.seocoo.worker.friend.entity.RxEvaluateSuccess;
import com.seocoo.worker.friend.entity.RxRefreshSuccess;
import com.seocoo.worker.order.entity.RspOrderInstallDetail;
import com.seocoo.worker.order.entity.RspWorkers;
import com.seocoo.worker.order.entity.RxCancelInstallSuccess;
import com.seocoo.worker.order.model.OrderInstallDetailModel;
import com.seocoo.worker.order.model.OrderInstallModel;
import com.seocoo.worker.order.req.ReqAppointmentTime;
import com.seocoo.worker.order.req.ReqOrderInstallDetail;
import com.seocoo.worker.order.widget.OrderDetailAddressView;
import com.seocoo.worker.order.widget.OrderDetailCommodityView;
import com.seocoo.worker.order.widget.OrderDetailParticularsView;
import com.seocoo.worker.order.widget.OrderDetailReceivingView;
import com.seocoo.worker.order.widget.OrderDetailWorkerView;
import com.seocoo.worker.order.widget.rsp.RspOrderDetailAddress;
import com.seocoo.worker.order.widget.rsp.RspOrderDetailParticulars;
import com.sfh.lib.event.BusEventManager;
import com.sfh.lib.mvvm.LiveDataMatch;
import com.sfh.lib.ui.MVVMActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * author : Ssp
 * date   : 2020/2/22 23:54
 * desc   : 订单详情
 */
public class OrderInstallDetailActivity extends MVVMActivity implements View.OnClickListener {

    private OrderDetailReceivingView order_receiving;
    private OrderDetailAddressView order_address;
    private OrderDetailParticularsView order_particulars;
    private OrderDetailCommodityView order_commodity;
    private OrderDetailParticularsView order_measure;
    private OrderDetailParticularsView install_info;
    private OrderDetailWorkerView worker_info;
    private TextView tv_remark;
    private String orderId;
    private TextView tv_title;
    private RspOrderInstallDetail mRspData;
    private TextView tv_cancel;
    private TextView tv_receiving;
    private ImageView iv_back;
    private TextView tv_appointment_install_time;
    private TextView tv_evaluate_workmate;
    private TextView tv_relevance_friends;
    private TextView tv_order_receiving;
    private BaseListImageFragment upLoadFileFragment;
    private LinearLayout ll_img;

    public static void start(Context context, String orderId) {
        Intent intent = new Intent(context, OrderInstallDetailActivity.class);
        intent.putExtra("orderId", orderId);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_install_detail_activity);
        orderId = getIntent().getStringExtra("orderId");
        initView();
        StatusBarUtil.setTranslucentForImageView(this, 0, tv_title);
        initListener();
        reFreshData();

        //取消安装监听
        BusEventManager.register(RxCancelInstallSuccess.class, rxCancelInstallSuccess -> {
            if (rxCancelInstallSuccess.isCancelSuccess()) {
                reFreshData();
            }
        });
        //评价工友成功监听
        BusEventManager.register(RxEvaluateSuccess.class, rxEvaluateSuccess -> {
            if (rxEvaluateSuccess.isSuccess()) {
                reFreshData();
            }
        });
        BusEventManager.register(RxRefreshSuccess.class, refreshSuccess -> {
            if (refreshSuccess.isSuccess()) {
                reFreshData();
            }
        });
    }

    private void reFreshData() {
        getViewModel(OrderInstallDetailModel.class).refreshData(new ReqOrderInstallDetail(orderId));
    }

    @LiveDataMatch
    public void onTakeSuccess() {
        BusEventManager.postEvent(new RxCancelInstallSuccess(true));
        reFreshData();
    }

    @LiveDataMatch
    public void onAddWorksSuccess() {
        reFreshData();
    }

    @LiveDataMatch
    public void onQuerySuccess(RspOrderInstallDetail data) {
        mRspData = data;
        tv_remark.setText(data.getRemark());
        initOrderDetailReceivingViewData(data);
        initOrderDetailAddressViewData(data);
        initOrderDetailParticularsViewData(data);
        initOrderDetailCommodityViewData(data);
        initOrderDetailMeasureViewData(data);
        initInstallMeasureViewData(data);
        initWorksViewData(data);
        initBottomView(data);
        String[] picList = data.getPicList();
        if (picList == null || picList.length == 0) {
            ll_img.setVisibility(View.GONE);
        } else {
            ll_img.setVisibility(View.VISIBLE);
            assert upLoadFileFragment != null;
            upLoadFileFragment.setImageCount(3, picList.length, false);
            upLoadFileFragment.setTv_title1("现场图片上传");
            upLoadFileFragment.setTv_title2("");
            ArrayList<RspImage> list = new ArrayList<>();
            for (String s : picList) {
                RspImage rspImage = new RspImage();
                rspImage.setFullPath(s);
                list.add(rspImage);
            }
            upLoadFileFragment.setNewData(list);
        }
    }

    private void initView() {
        tv_title = findViewById(R.id.tv_title);
        iv_back = findViewById(R.id.iv_back);
        order_receiving = findViewById(R.id.order_receiving);
        order_address = findViewById(R.id.order_address);
        order_particulars = findViewById(R.id.order_particulars);
        order_commodity = findViewById(R.id.order_commodity);
        order_measure = findViewById(R.id.order_measure);
        install_info = findViewById(R.id.install_info);
        worker_info = findViewById(R.id.worker_info);
        tv_remark = findViewById(R.id.tv_remark);

        tv_cancel = findViewById(R.id.tv_cancel);
        tv_order_receiving = findViewById(R.id.tv_order_receiving);
        tv_receiving = findViewById(R.id.tv_receiving);
        tv_appointment_install_time = findViewById(R.id.tv_appointment_install_time);
        tv_evaluate_workmate = findViewById(R.id.tv_evaluate_workmate);
        tv_relevance_friends = findViewById(R.id.tv_relevance_friends);
        ll_img = findViewById(R.id.ll_img);
        upLoadFileFragment = (BaseListImageFragment) getSupportFragmentManager().findFragmentById(R.id.upLoadFileFragment);
    }

    private void initListener() {
        tv_cancel.setOnClickListener(this);
        tv_receiving.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        tv_appointment_install_time.setOnClickListener(this);
        tv_evaluate_workmate.setOnClickListener(this);
        tv_relevance_friends.setOnClickListener(this);
        tv_order_receiving.setOnClickListener(this);
    }

    private void initOrderDetailReceivingViewData(RspOrderInstallDetail data) {
        //订单状态 400 取消安装 401 待接单 402 待取货 403 待安装 501 待评价
        String orderStatus = "";
        if (TextUtils.equals("400", data.getOrderStatus())) {
            orderStatus = "取消安装";
        }
        if (TextUtils.equals("401", data.getOrderStatus())) {
            orderStatus = "待接单";
        }
        if (TextUtils.equals("402", data.getOrderStatus())) {
            orderStatus = "待取货";
        }
        if (TextUtils.equals("403", data.getOrderStatus())) {
            orderStatus = "待安装";
        }

        String isAppraise = data.getIsAppraise();
        if (TextUtils.equals("501", data.getOrderStatus()) && TextUtils.equals("0", isAppraise)) {
            orderStatus = "等待评价工友";
        }
        if (TextUtils.equals("501", data.getOrderStatus()) && TextUtils.equals("1", isAppraise)) {
            orderStatus = "";
        }
        order_receiving.initData(data.getCommission(), orderStatus);
    }

    private void initOrderDetailAddressViewData(RspOrderInstallDetail data) {
        RspOrderDetailAddress rspOrderDetailAddress = new RspOrderDetailAddress();
        rspOrderDetailAddress.setCargoAddress(data.getMerchantName());
        rspOrderDetailAddress.setCargoAddressDetail(data.getMerchantProvince() + data.getMerchantCity() + data.getMerchantDistrict() + data.getMerchantAddress());
        rspOrderDetailAddress.setUserAddress(data.getUserProvince() + data.getUserCity() + data.getUserDistrict() + data.getUserCommunity() + data.getUserDoorPlate());
        rspOrderDetailAddress.setUserName(data.getConsignee());
        rspOrderDetailAddress.setUserPhone(data.getContact());
        rspOrderDetailAddress.setMerchantContact(data.getMerchantContact());
        rspOrderDetailAddress.setPickupCode(data.getPickupCode());
        order_address.initData(rspOrderDetailAddress);
        String status = data.getOrderStatus();
        order_address.setVisibilityPickUpCode(false);

        if (TextUtils.equals("401", status)) {
            order_address.setVisibilityPhone(View.GONE);
        }
    }

    private void initOrderDetailCommodityViewData(RspOrderInstallDetail data) {
        order_commodity.initData(data.getGoodsList(), data.getOrderStatus());
        order_commodity.setScoreName(data.getMerchantName());
    }

    private void initOrderDetailParticularsViewData(RspOrderInstallDetail data) {

        order_particulars.setTv_title("订单详情");
        List<RspOrderDetailParticulars> list = new ArrayList<>();
        RspOrderDetailParticulars rsp1 = new RspOrderDetailParticulars();
        rsp1.setName("订单编号：");
        rsp1.setContent(data.getOrderNo());
        list.add(rsp1);
        RspOrderDetailParticulars rsp2 = new RspOrderDetailParticulars();
        rsp2.setName("下单时间：");
        rsp2.setContent(data.getAddTime());
        list.add(rsp2);
        String orderPrice = data.getOrderPrice();
        if (!TextUtils.isEmpty(orderPrice)) {
            Double aDouble = Double.valueOf(orderPrice);
            if (aDouble > 0) {
                RspOrderDetailParticulars rsp3 = new RspOrderDetailParticulars();
                rsp3.setName("订单总额：");
                rsp3.setContent(orderPrice);
                list.add(rsp3);
            }
        }
        String payTime = data.getPayTime();
        if (TextUtils.isEmpty(payTime)) {
            payTime = "";
        }
        RspOrderDetailParticulars rsp4 = new RspOrderDetailParticulars();
        rsp4.setName("支付时间：");
        rsp4.setContent(payTime);
        list.add(rsp4);
        String channelType = data.getChannelType();

        // 支付方式 1-支付宝 2-微信
        if (TextUtils.equals("2", channelType)) {
            RspOrderDetailParticulars rsp5 = new RspOrderDetailParticulars();
            rsp5.setName("支付方式：");
            channelType = "微信支付";
            rsp5.setContent(channelType);
            list.add(rsp5);
        }
        if (TextUtils.equals("1", channelType)) {
            RspOrderDetailParticulars rsp5 = new RspOrderDetailParticulars();
            rsp5.setName("支付方式：");
            channelType = "支付宝支付";
            rsp5.setContent(channelType);
            list.add(rsp5);
        }
        String pickupCode = data.getPickupCode();
        String orderStatus = data.getOrderStatus();
        String installTime = data.getInstallTime();

        if (TextUtils.isEmpty(installTime) && (TextUtils.equals("402", orderStatus) || TextUtils.equals("403", orderStatus))) {
            RspOrderDetailParticulars rsp6 = new RspOrderDetailParticulars();
            rsp6.setName("取货码：");
            rsp6.setContent(pickupCode);
            list.add(rsp6);
        }
        order_particulars.initData(list);
    }

    private void initOrderDetailMeasureViewData(RspOrderInstallDetail data) {

        order_measure.setTv_title("测量详情");
        List<RspOrderDetailParticulars> list = new ArrayList<>();
        RspOrderDetailParticulars rsp1 = new RspOrderDetailParticulars();
        rsp1.setName("接单时间：");
        rsp1.setContent(data.getMeasureCreatedTime());
        list.add(rsp1);
        RspOrderDetailParticulars rsp2 = new RspOrderDetailParticulars();
        rsp2.setName("测量人：");
        rsp2.setContent(data.getMeasureName());
        list.add(rsp2);
        RspOrderDetailParticulars rsp3 = new RspOrderDetailParticulars();
        rsp3.setName("预约测量时间：");
        rsp3.setContent(data.getMeasureTime());
        list.add(rsp3);
        order_measure.initData(list);
    }

    private void initInstallMeasureViewData(RspOrderInstallDetail data) {

        install_info.setTv_title("安装详情");
        List<RspOrderDetailParticulars> list = new ArrayList<>();

        String installTime = data.getInstallTime();
        if (TextUtils.isEmpty(installTime)) {
            installTime = "";
        }
        RspOrderDetailParticulars rsp4 = new RspOrderDetailParticulars();
        rsp4.setName("预约安装时间：");
        rsp4.setContent(installTime);
        list.add(rsp4);
        install_info.initData(list);
        String status = data.getOrderStatus();
        if (TextUtils.isEmpty(status)) {
            status = "0";
        }
        int parseInt = Integer.parseInt(status);
        if (parseInt >= 403 && !TextUtils.isEmpty(installTime)) {
            install_info.setVisibility(View.VISIBLE);
        } else {
            install_info.setVisibility(View.GONE);
        }
    }

    private void initWorksViewData(RspOrderInstallDetail data) {
        List<RspWorkers> workers = data.getWorkers();
        if (workers == null || workers.size() == 0) {
            worker_info.setVisibility(View.GONE);
        } else {
            worker_info.setVisibility(View.VISIBLE);
            worker_info.setTv_title("关联工友");
            worker_info.initData(workers);
        }
    }

    @Override
    public void onClick(View view) {

        if (mRspData == null) {
            return;
        }

        switch (view.getId()) {

            case R.id.tv_cancel:
                //取消安装
                OrderCancelInstallationActivity.start(this, mRspData.getInstallId());
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_receiving:
                //确认收货
                getViewModel(OrderInstallModel.class).packUpOrder(mRspData.getOrderId());
                break;
            case R.id.tv_relevance_friends:
                // 关联工友
                OrderRelevanceWorkmateActivity.startContentUI(this, mRspData.getInstallId());
                break;
            case R.id.tv_appointment_install_time:
                //预约安装时间
                initTimeSelect("预约安装时间", (date, v) -> {
                    @SuppressLint("SimpleDateFormat") String format = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
                    ReqAppointmentTime reqAppointmentTime = new ReqAppointmentTime();
                    reqAppointmentTime.setInstallId(mRspData.getInstallId());
                    reqAppointmentTime.setInstallTime(format);
                    getViewModel(OrderInstallModel.class).appointmentTimeOrder(reqAppointmentTime);
                });
                break;
            case R.id.tv_evaluate_workmate:
                //平价工友
                FriendEvaluateActivity.start(this, mRspData.getInstallId(), mRspData.getOrderId());
                break;
            case R.id.tv_order_receiving:
                //接单
                getViewModel(OrderInstallModel.class).takeInstallOrder(mRspData.getOrderId());
                break;
            default:
                break;
        }
    }

    /**
     * 选择时间
     */
    @SuppressLint("SimpleDateFormat")
    private void initTimeSelect(String title, OnTimeSelectListener timeSelectListener) {
        long timeMillis = System.currentTimeMillis();
        SimpleDateFormat year = new SimpleDateFormat("yyyy");
        SimpleDateFormat moth = new SimpleDateFormat("MM");
        SimpleDateFormat day = new SimpleDateFormat("dd");
        Date date = new Date(timeMillis);
        Calendar startDate = Calendar.getInstance();
        startDate.set(Integer.parseInt(year.format(date)), Integer.parseInt(moth.format(date)) - 1, Integer.parseInt(day.format(date)));
        Calendar endDate = Calendar.getInstance();
        endDate.set(2080, 12, 30);
        Calendar selectedDate = Calendar.getInstance();
        TimePickerBuilder timePickerBuilder = new TimePickerBuilder(this, timeSelectListener)
                .setTitleText(title)
                //时间选择器 ，自定义布局
                .setDividerColor(Color.parseColor("#999999"))
                .setDividerType(WheelView.DividerType.FILL)
                .setContentTextSize(20)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                //设置选中项的颜色
                .setTextColorCenter(Color.parseColor("#333333"))
                .setLabel("年", "月", "日", "时", "分", "")
                .isCenterLabel(false)
                .isDialog(true)
                //设置两横线之间的间隔倍数  m
                .setLineSpacingMultiplier(2.0f)
                .setTextXOffset(0, 0, 0, 0, 0, 0)
                .setOutSideCancelable(false)
                .setType(new boolean[]{true, true, true, true, true, false});
        timePickerBuilder.build().show();
    }

    private void initBottomView(RspOrderInstallDetail data) {
        //400 取消安装 401 待接单 402 待取货 403 待安装 501 待评价
        String status = data.getOrderStatus();
        if (TextUtils.equals("401", status)) {
            tv_order_receiving.setVisibility(View.VISIBLE);
        } else {
            tv_order_receiving.setVisibility(View.GONE);
        }

        if (TextUtils.equals("402", status)) {
            tv_receiving.setVisibility(View.VISIBLE);

        } else {
            tv_receiving.setVisibility(View.GONE);

        }
        String installTime = data.getInstallTime();
        if (TextUtils.equals("402", status) && TextUtils.isEmpty(installTime)) {
            tv_cancel.setVisibility(View.VISIBLE);
        } else {
            tv_cancel.setVisibility(View.GONE);
        }

        if (TextUtils.equals("403", status) && TextUtils.isEmpty(installTime)) {
            tv_appointment_install_time.setVisibility(View.VISIBLE);
        } else {
            tv_appointment_install_time.setVisibility(View.GONE);
        }

        if (TextUtils.equals("403", status) && !TextUtils.isEmpty(installTime)) {
            tv_relevance_friends.setVisibility(View.VISIBLE);
        } else {
            tv_relevance_friends.setVisibility(View.GONE);
        }

        String isAppraise = data.getIsAppraise();

        if (TextUtils.equals("501", status) && TextUtils.equals("0", isAppraise)) {
            tv_evaluate_workmate.setVisibility(View.VISIBLE);
        } else {
            tv_evaluate_workmate.setVisibility(View.GONE);
        }
    }
}
